package 聊天室;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class server implements Runnable{
    static ServerSocket ss;

    static {
        try {
            ss = new ServerSocket(8888);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException,RuntimeException,IllegalThreadStateException {
        /*while (true){
            //监听客户端的链接
            Socket socket = ss.accept();
            //从连接通道中获取数据
            InputStream is = socket.getInputStream();
            //用高级流来提高读取的速度，并且防止中文乱码
            InputStreamReader isr = new InputStreamReader(is);
            int b;
            while ((b = isr.read()) != -1){
                System.out.print((char) b + " ");
            }
            System.out.println();
            //释放资源
            socket.close();
        }*/
        //ss.close();
        //创建服务端对象ServerSocket并绑定端口10000

        server mt = new server();
        Thread t1 = new Thread(mt);
        Thread t2 = new Thread(mt);
        Thread t3 = new Thread(mt);

        System.out.println("-----服务端已经开启-----");
        t1.start();
        t2.start();
        t3.start();



    }
    public static void mythread() throws IOException, InterruptedException {
        //监听客户端的链接
        Socket socket = null;
        socket = ss.accept();
        while (socket == null) {
            if (socket == null) {
                Thread.currentThread().wait();
            }
        }

        //从连接通道中获取数据
        InputStream is = socket.getInputStream();
        //用高级流来提高读取的速度，并且防止中文乱码
        InputStreamReader isr = new InputStreamReader(is);
        StringBuffer sb = new StringBuffer();
        int b;
        while ((b = isr.read()) != -1){
            sb.append((char) b);
        }
        System.out.print(Thread.currentThread().getName()+":"+ sb);
        System.out.println();
        //返回数据
        //监听客户端的链接
//        Socket socket1 = null;
//        socket1 = ss.accept();
//        while (socket1 == null) {
//            if (socket1 == null) {
//                Thread.currentThread().wait();
//            }
//        }
//        OutputStream out = socket1.getOutputStream();
//        out.write(sb.toString().getBytes());


    }

    @Override
    public void run() {
        while (true) {
            try {
                mythread();
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
